package com.clei.Y2023.M10.D13.com;

import com.clei.Y2023.M10.D13.sender.MqttMsgSender;
import com.clei.Y2023.M10.D13.sender.MsgSender;
import com.clei.Y2023.M10.D13.sender.TestMsgSender;
import com.clei.utils.PrintUtil;

import java.util.concurrent.BlockingQueue;

/**
 * 串口消息处理
 *
 * @author Y
 * @date 2023-10-24
 */
public class ComMessageHandler implements Runnable {

    /**
     * 阻塞队列
     */
    private final BlockingQueue<String> msgQueue;

    /**
     * 消息转发器
     */
    private final MsgSender msgSender;

    public ComMessageHandler(BlockingQueue<String> msgQueue, boolean testEnabled) {
        this.msgQueue = msgQueue;
        this.msgSender = testEnabled ? new TestMsgSender() : new MqttMsgSender();
    }

    @Override
    public void run() {
        try {
            PrintUtil.log("串口线程已运行");
            while (true) {
                // 从阻塞队列取数据
                String str = this.msgQueue.take();
                PrintUtil.log(str);
                // 数据转发
                transfer(str);
            }
        } catch (InterruptedException e) {
            PrintUtil.log("线程执行异常 ", e);
        }
    }

    /**
     * 转发
     *
     * @param str 数据
     */
    private void transfer(String str) {
        // 非心跳数据
        if (!str.startsWith("823030") && !str.startsWith("823639")) {
            this.msgSender.send(str);

            /*try (FileWriter fw = new FileWriter("D:\\Temp\\293kOutput.txt", true);
                 BufferedWriter bw = new BufferedWriter(fw)) {
                bw.write(str);
                bw.newLine();
                bw.flush();
            } catch (Exception e) {
                PrintUtil.log("写入文件出错 ",e);
            }*/
        }
    }
}
